import React from 'react'
import PropTypes from 'prop-types'
import InputForm from '../controls/InputForm.jsx';
import CampaignService from '../../services/CampaignService.js'
import CancelOnUnmount from '../../services/CancelOnUnmount.js'
import GeoService from '../../services/GeoService.js'
import GeoCheckboxList from '../controls/GeoCheckboxList.jsx'
import Recommendations from '../controls/Recommendations.jsx'

export default class GeoTargeting extends React.Component {

    static propTypes = {
        campaignId: PropTypes.string.isRequired,
    };

    constructor(props) {
        super(props);

        this.handleSaveButtonClicked = this.handleSaveButtonClicked.bind(this);
        this.handleToggleGeo = this.handleToggleGeo.bind(this);
        this.handleGetIsGeoChecked = this.handleGetIsGeoChecked.bind(this);
        this.handleGeoSearchChanged = this.handleGeoSearchChanged.bind(this);
        this.handleRetry = this.handleRetry.bind(this);
        this.initialCityLoad = this.initialCityLoad.bind(this);

        this.state = {
            isError: false,
            isSaving: false,
            isLoadingGeos: true,
            searchText: '',
            isLoadingSelectedGeos: true,
            // 用来记录 选中的 checkbox
            selectedGeoIds: [],
            // 存放查询到的城市数据
            allGeos: [],
            onRetry: this.initialCityLoad
        };
        this.throttle = this.throttle.bind(this)
        let filterTextChange = this.throttle(500, this.handleGeoSearchChanged, 500)
        this.filterTextChange = filterTextChange
    }
    // 组件挂载之后，执行的方法
    componentDidMount() {
        // 获取 城市所有数据 和 选中的城市 IDs
        this.initialCityLoad();
    }

    componentWillUnmount() {
        CancelOnUnmount.handleUnmount(this);
    }

    // 拿到所有的城市数据
    refreshAllCities() {
        const promise = GeoService.getAllCities('city_name', false).then(allCities => {
            this.setState({
                allGeos: allCities,
                isLoadingGeos: false
            });
        });

        CancelOnUnmount.track(this, promise);

        return promise;
    }

    initialCityLoad() {
        // 告诉组件，我现在正在加载数据
        this.setState({
            isLoadingGeos: true,
            isLoadingSelectedGeoIds: true
        });
        // 拿到所有的城市数据
        const refreshAllPromise = this.refreshAllCities();
        // 获取选中的IDs
        const getSelectedPromise = CampaignService.getSelectedGeoIds(this.props.campaignId).then(selectedIds => {
            this.setState({
                selectedGeoIds: selectedIds,
                isLoadingSelectedGeoIds: false
            });
        });
        // 用来处理 获取数据异常
        CancelOnUnmount.track(this, Promise.all([refreshAllPromise, getSelectedPromise]).catch(() => {
            this.setState({
                isError: true,
                isLoadingGeos: false,
                isLoadingSelectedGeoIds: false,
                onRetry: this.initialCityLoad
            });
        }));
    }


    handleRetry() {
        this.setState({
            isError: false
        });

        this.state.onRetry();
    }
    // 手动选择 checkbox
    handleToggleGeo(item) {
        const ids = this.state.selectedGeoIds;
        // 删除已经选中的
        if (ids.indexOf(item.geoId) >= 0) {
            this.setState({
                selectedGeoIds: ids.filter(id => id !== item.geoId)
            });
        } else { // 添加没有选中的
            this.setState({
                selectedGeoIds: ids.concat(item.geoId)
            });
        }
    }
    // 判断 checkbox 是否选中
    handleGetIsGeoChecked(item) {
        return this.state.selectedGeoIds.indexOf(item.geoId) >= 0;
    }

    // 用户输入搜索内容 到时候，双向绑定 onchange 触发的事件
    handleGeoSearchChanged(newSearch) {
        // if (newSearch !== undefined) {
        //     this.setState({
        //         searchText: newSearch
        //     });
        // } else {
        //     newSearch = this.state.searchText;
        // }
        // 如果用户没有输入任何内容，则显示所有的数据
        if (!newSearch || newSearch.length === 0) {
            this.refreshAllCities().catch(() => {
                this.setState({
                    isError: true,
                    onRetry: this.handleGeoSearchChanged
                });
            });
        } else {
            CancelOnUnmount.track(this, GeoService.getCitiesPaged(newSearch, 'city_name', false, 0, 100).then(someCities => {
                this.setState({
                    allGeos: someCities
                });
            }).catch(() => {
                this.setState({
                    isError: true,
                    onRetry: this.handleGeoSearchChanged
                });
            }));
        }
    }
    // 保存选中的 checkbox 
    handleSaveButtonClicked() {
        this.setState({
            isSaving: true
        });

        CancelOnUnmount.track(
            this,
            CampaignService
                // 保存用户选中的值
                .saveSelectedGeoIds(this.props.campaignId, this.state.selectedGeoIds)
                .catch(() => {
                    this.setState({
                        isError: true,
                        onRetry: this.handleSaveButtonClicked
                    });
                })
                .finally(() => {
                    this.setState({
                        isSaving: false
                    });
                })
        );
    }

    throttle (delay, method, duration){
        var timer = null;
        var begin = new Date();
        const that = this
        return function(){
            let newSearch = arguments[0]
            console.log(newSearch)
            if (newSearch !== undefined) {
                that.setState({
                    searchText: newSearch
                });
            } else {
                newSearch = that.state.searchText;
            }
            var context = that;
            var args = arguments;
            var current = new Date();
            clearTimeout(timer);
            if(current-begin>=duration){
                console.log('我执行了')
                method.apply(context,args);
                begin=current;
            }else{
                timer=setTimeout(function(){
                    console.log('我执行了1111')
                    method.apply(context,args);
                },delay);
            }
        }
    }

    // throttle (delay, action) {
    //     const that = this
    //     var timer = null;
    //     var last = 0
    //     return function () {
    //         let newSearch = arguments[0]
    //         console.log(newSearch)
    //         if (newSearch !== undefined) {
    //             that.setState({
    //                 searchText: newSearch
    //             });
    //         } else {
    //             newSearch = that.state.searchText;
    //         }
    //         var curr = +new Date()
    //         if (curr - last > delay) {
                
    //             action.apply(that, arguments)
    //         } else {
    //             timer = setTimeout(function(){
                    
    //                 action.apply(that,arguments);
    //             },delay);
    //         }
    //         last = curr
    //     }
    // }

    render() {
        let { searchText, allGeos } = this.state
        return (
            <div>
                <InputForm
                    onSubmit={this.handleSaveButtonClicked}
                    onRetry={this.handleRetry}
                    isError={this.state.isError}
                    isLoading={this.state.isLoadingGeos || this.state.isLoadingSelectedGeoIds}
                    isSaving={this.state.isSaving}>
                    <GeoCheckboxList
                        items={allGeos}
                        searchText={searchText}
                        onSearchChanged={this.filterTextChange}
                        onToggleItem={this.handleToggleGeo}
                        getIsChecked={this.handleGetIsGeoChecked}
                    />
                </InputForm>
                <Recommendations recommendationType='CAMPAIGN_GEO_RECOMMENDATIONS' campaignId={this.props.campaignId} />
            </div>
        );
    }
}
